g_dirname = ''
g_object_name = ''
g_object_name_type = ''

var sub_num = 0;
var aliosstpic = "";

//上传成功后的文件地址
aliosstpic = []
var toalioss_type = false;

now = timestamp = Date.parse(new Date()) / 1000;

var policyText = {
    "expiration": "2060-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
        ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
};

var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {asBytes: true});
var signature = Crypto.util.bytesToBase64(bytes);

function get_dirname() {
    dir = dirName;
    if (dir != '' && dir.indexOf('/') != dir.length - 1) {
        dir = dir + '/'
    }
    //alert(dir)
    g_dirname = dir
}

function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename) {
    g_object_name += "${filename}"
    return ''
}

function get_uploaded_object_name(filename) {
    tmp_name = g_object_name
    tmp_name = tmp_name.replace("${filename}", filename);
    return tmp_name
}

function set_upload_param(up, filename, ret) {
    g_object_name = g_dirname;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key': g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

function set_upload_param_head(up, filename, ret) {
    g_object_name = g_dirname;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key': g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

function removeImg(obj, index) {
    imgSrc.splice(index, 1);
    var boxId = content_img;
    addNewContent(boxId);
}

//图片展示
function addNewContent(obj) {
    // console.log(imgSrc)
    $(obj).html("");
    for (var a = 0; a < imgSrc.length; a++) {
        var oldBox = $(obj).html();
        $(obj).html(oldBox + '<li class="content-img-list-item"><img src="' + imgSrc[a] + '" alt="">' +
            '<div class="hide"><a index="' + a + '" class="delete-btn"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a></div></li>');
    }
    let number = $(content_img).children("li").length;
    if (number >= photo_num_type) {
        $(".file").hide();
    } else {
        $(".file").show();
    }

}

//返回文件路径
function ReturnTpic() {
    return aliosstpic
}

var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: ["upload_ali_tuwen", "upload_ali_weitoutiao"],
    //multi_selection: false,
    // container: document.getElementById('container'),
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    url: 'http://oss.aliyuncs.com',

    init: {
        // PostInit: function() {
        //     document.getElementById('sub_alioss').onclick = function() {
        //         set_upload_param(uploader, '', false);
        //         return false;
        //     };
        // },
//当文件添加到上传队列后触发
        FilesAdded: function (up, files) {
            console.log(files)
            var type = files[0].type;
            if (type.toLowerCase() == "image/jpeg" || type.toLowerCase() == "image/png" || type.toLowerCase() == "image/gif") {
                var reader = new FileReader();
                reader.onload = (function (file) {
                    return function (e) {

                        //---提取base64代码
                        // var base64 = "";
                        // if (this.result.length > 20) {
                        //     var index = this.result.indexOf(",");
                        //     if (index > 0) {
                        //         base64 = this.result.substr(index + 1);
                        //     }
                        // }

                        //this.result---是直接可以用的base64，
                        imgSrc.push(this.result);
                        aliosstpic.push(files[0].name)
                        addNewContent(content_img);
                        // $("#sub_alioss").show();
                    };
                })(files[0]);
                //---不知道用途
                reader.readAsDataURL(files[0].getNative());
            }
            // plupload.each(files, function(file) {
            // 	document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
            // 	+'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
            // 	+'</div>';
            // });


            //---操作图片
            // 鼠标经过显示删除按钮
            $(content_img).on('mouseover', '.content-img-list-item', function () {
                $(this).children('div').removeClass('hide');
            });
            // 鼠标离开隐藏删除按钮
            $(content_img).on('mouseleave', '.content-img-list-item', function () {
                $(this).children('div').addClass('hide');
            });
            // 单个图片删除
            $(content_img).on("click", '.content-img-list-item a .glyphicon-trash', function () {
                var index = $(this).parent().parent().parent().index();
                if (index != -1) {
                    imgSrc.splice(index, 1);
                    up.files.splice(index, 1);
                    var boxId = content_img;
                    addNewContent(boxId);
                    // $(content_img).children("li").length
                    if (imgSrc.length < 9) { //显示上传按钮
                        $('.content-img .file').show();
                    }
                }
            });

        },
//当队列中的某一个文件正要开始上传前触发
        BeforeUpload: function (up, file) {
            // console.log(file)
            get_dirname();
            console.log(dirName)
            set_upload_param(up, file.name, true);
        },
//上传过程中
        UploadProgress: function (up, file) {
            // var d = document.getElementById(file.id);
            // d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            // var prog = d.getElementsByTagName('div')[0];
            // var progBar = prog.getElementsByTagName('div')[0]
            // progBar.style.width= 2*file.percent+'px';
            // progBar.setAttribute('aria-valuenow', file.percent);
        },
//当文件从上传队列移除后触发
        FileUploaded: function (up, file, info) {
            console.log(info)
            if (info.status == 200) {
                sub_num++
                // aliosstpic.push(host + dirName + "/" + file.name)
                if (sub_num == imgSrc.length) {
                    setTimeout(function () {
                        alert("发布成功");
                        window.location.href = "create.html";
                    }, 500);
                }
            } else {
                alert("文件上传失败,请过一会重试")
            }
        },

        Error: function (up, err) {
            document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
        }
    }
});

//返回文件
function Return_videotpic() {
    return aliosstpic
}


var uploader_video = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: "drop",
    multi_selection: false,
    multiple_queues : false,
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    url: 'http://oss.aliyuncs.com',
    filters: {
        max_file_size: '60mb', //最大上传文件大小（格式100b, 10kb, 10mb, 1gb）
        mime_types: [//允许文件上传类型
            {title: "files", extensions: "mpg,m4v,mp4,flv,3gp,mov,avi,rmvb,mkv,wmv"}
        ]
    },

    init: {
//当文件添加到上传队列后触发
        FilesAdded: function (up, files) {
            console.log(up)
            // var objUrl = getObjectURL(files[0])
            // $("#video0").attr("src", window.URL.createObjectURL(files[0]));
            if (uploader_video.files.length > 1) {
                alert("只能上传一个文件");
                uploader_video.removeFile(files[0]);
            } else {
                plupload.each(files, function (file) {
                    document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
                        + '<div class="progress"><div class="progress-bar" style="width: 0"></div></div>'
                        + '</div>';
                });
                $("#drop").hide();
                aliosstpic.video_name = files[0].name;
                aliosstpic.size = Math.round(files[0].size / 1024);
                aliosstpic.img_name = "";
                // size / 1048576
                // set_upload_param(uploader_video, '', false);
            }
        },
//当队列中的某一个文件正要开始上传前触发
        BeforeUpload: function (up, file) {
            // console.log(file)
            get_dirname();
            set_upload_param(up, file.name, true);
        },
//上传过程中
        UploadProgress: function (up, file) {
            var d = document.getElementById(file.id);
            d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            var prog = d.getElementsByTagName('div')[0];
            var progBar = prog.getElementsByTagName('div')[0]
            progBar.style.width = 10 * file.percent + 'px';
            progBar.setAttribute('aria-valuenow', file.percent);
        },
//当文件从上传队列移除后触发
        FileUploaded: function (up, file, info) {
            console.log(info)
            if (info.status == 200) {
                setTimeout(function () {
                    alert("发布成功");
                    window.location.href = "create.html";
                }, 1000);
            } else {
                alert("文件上传失败,请过一会重试")
            }
        },
        Error: function (up, err) {
            document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
        }
    }
});

var uploader_video_img = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: "drop2",
    multi_selection: false,
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    url: 'http://oss.aliyuncs.com',
    filters: {
        max_file_size: '2mb', //最大上传文件大小（格式100b, 10kb, 10mb, 1gb）
        mime_types: [//允许文件上传类型
            {title: "files", extensions: "jpg,gif,png,jpeg"}
        ]
    },

    init: {
//当文件添加到上传队列后触发
        FilesAdded: function (up, files) {
            console.log(up)
            if (uploader_video.files.length > 1) {
                alert("只能上传一个文件。");
                uploader_video.removeFile(files[0]);
            } else {
                plupload.each(files, function (file) {
                    document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
                        + '<div class="progress"><div class="progress-bar" style="width: 0"></div></div>'
                        + '</div>';
                });
                $("#drop2").hide();
                aliosstpic.img_name = files[0].name;
                // size / 1048576
                // set_upload_param(uploader_video, '', false);
            }
        },
//当队列中的某一个文件正要开始上传前触发
        BeforeUpload: function (up, file) {
            // console.log(file)
            get_dirname();
            set_upload_param(up, file.name, true);
        },
//上传过程中
        UploadProgress: function (up, file) {
            var d = document.getElementById(file.id);
            d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            var prog = d.getElementsByTagName('div')[0];
            var progBar = prog.getElementsByTagName('div')[0]
            progBar.style.width = 10 * file.percent + 'px';
            progBar.setAttribute('aria-valuenow', file.percent);
        },
//当文件从上传队列移除后触发
        FileUploaded: function (up, file, info) {
            console.log(info)
            if (info.status == 200) {
                setTimeout(function () {
                    // alert("发布成功");
                    // window.location.href = "create.html";
                }, 500);
            } else {
                alert("文件上传失败,请过一会重试")
            }
        },
        Error: function (up, err) {
            document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
        }
    }
});

var uploader_head_img = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: "file0",
    //multi_selection: false,
    // container: document.getElementById('container'),
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    url: 'http://oss.aliyuncs.com',

    init: {
//当文件添加到上传队列后触发
        FilesAdded: function (up, files) {
            console.log(files)
            var type = files[0].type;
            if (type.toLowerCase() == "image/jpeg" || type.toLowerCase() == "image/png" || type.toLowerCase() == "image/gif") {
                var reader = new FileReader();
                reader.onload = (function (file) {
                    return function (e) {

                        //this.result---是直接可以用的base64，
                        // imgSrc.push(this.result);
                        $("#user_headimg").attr("src", this.result);
                        $("#headimg_name").text(files[0].name);
                        aliosstpic.push(files[0].name);

                    };
                })(files[0]);
                //---不知道用途
                reader.readAsDataURL(files[0].getNative());
            }
        },
//当队列中的某一个文件正要开始上传前触发
        BeforeUpload: function (up, file) {
            // console.log(file)
            get_dirname();
            set_upload_param_head(up, file.name, true);
        },
//上传过程中
        UploadProgress: function (up, file) {

        },
//当文件从上传队列移除后触发
        FileUploaded: function (up, file, info) {
            if (info.status == 200) {
                console.log(info)
            } else {
                alert("文件上传失败,请过一会重试")
            }
        },

        Error: function (up, err) {
            document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
        }
    }
});

uploader.init()
uploader_video.init()
uploader_video_img.init()
uploader_head_img.init()
